import re

from flask import Blueprint, request, jsonify, render_template
import json
import requests

from methods.dangdangOs import get_publish_info_by_isbn, get_second_classify_by_first_classify, submitBase, submitSecond
from utils.tools import compare_labels, dcc_book_detail

bp = Blueprint("dangdangOs", __name__, url_prefix="/dangdangOs")


@bp.route('/test', methods=['get'])
def test():
    return "test"


@bp.route('/loginPage', methods=['get'])
def loginPage():
    return render_template('dangdang.html')


@bp.route('/loginApi', methods=['post'])
def loginApi():
    keys = ['verifyKey', 'verifyCode', 'systemId', 'url', 'role', 'code', 'account', 'business', 'warehouseType',
            'warehouseId', 'password']
    data = {key: request.form.get(key) for key in keys}
    response = requests.post('http://vrm.dangdang.com/base/doLogin', data=data, verify=False)
    response_json = json.loads(response.text)
    if response_json['status'] == 200:
        phpsessid = re.search(r'VRM_SID=([^;]+)', response.headers['set-cookie']).group(1)
        return {'status': 200, 'message': 'ok', 'phpsessid': phpsessid}
    else:
        return response_json


@bp.route('/verifyCode', methods=['get'])
def verifyCode():
    response = requests.get('http://vrm.dangdang.com/base/verifyCode/refresh')
    response_json = json.loads(response.text)
    return response_json


@bp.route('/checkSession', methods=['get'])
def checkSession():
    phpsessid = request.args.get('phpsessid')
    if not phpsessid:
        return "请传入phpsessid"
    cookies = {
        'VRM_SID': phpsessid,
    }
    headers = {}
    data = {
        'pageNum': '1',
        'pageSize': '5',
    }
    response = requests.post('http://vrm.dangdang.com/notice/query', cookies=cookies, headers=headers, data=data,
                             verify=False)
    response_str = response.text
    if bool(re.search(r'<html.*?>.*?</html>', response_str, re.IGNORECASE | re.DOTALL)) or response_str == '':
        return {'code': 0, 'message': '登录过期'}
    else:
        response_json = json.loads(response_str)
        if response_json['status'] == 200:
            return {'code': 200, 'message': '当当登录状态未过期'}
        else:
            return {'code': 0, 'message': '登录过期'}


@bp.route('/publishProduct', methods=['post'])
def publishProduct():
    data = request.get_json()
    dcc_token = data.get('dcc_token')
    serial_no = data.get('serial_no')
    session_id = data.get('session_id')
    YXFLID2 = data.get('YXFLID2')  # 二级分类ID
    YXFLID3 = data.get('YXFLID3')  # 三级分类ID
    discount = data.get('discount')  # 首次进折
    SJSL = data.get('SJSL')  # 建议首进数量
    if not dcc_token or not serial_no or not dcc_token or not session_id or not YXFLID2 or not YXFLID3 or not discount or not SJSL:
        return {'code': 0, 'message': '请传入必填项！'}
    book_details_json = dcc_book_detail(serial_no, dcc_token)
    if book_details_json['code'] != 200:
        return {'code': 0, 'message': book_details_json['message']}
    book_details_json = book_details_json['data']
    # 提交基础信息待修改
    result = submitBase(book_details_json, session_id, YXFLID2, YXFLID3, discount, SJSL)
    return result

@bp.route('/fillProduct', methods=['post'])
def fillProduct():
    data = request.get_json()
    dcc_token = data.get('dcc_token')
    serial_no = data.get('serial_no')
    session_id = data.get('session_id')
    productId = data.get('productId')  # 当当商品id
    if not dcc_token or not serial_no or not dcc_token or not session_id or not productId:
        return {'code': 0, 'message': '请传入必填项！'}
    book_details_json = dcc_book_detail(serial_no, dcc_token)
    if book_details_json['code'] != 200:
        return {'code': 0, 'message': book_details_json['message']}
    book_details_json = book_details_json['data']
    # 丰富信息
    result = submitSecond(book_details_json, session_id, productId)
    return result